<?php
/**
 * 转盘抽奖管理
 */
namespace Admin\Controller;
use Admin\BaseController;
use Common\Model\CouponModel;
use Common\Model\EventsModel;
use Common\Model\PointLotteryModel;
use Common\Model\SignLuckyModel;
use Common\Model\TurnModel;
use Common\Model\UtilsModel;
use Think\Page;
class TurnLotteryController extends BaseController{
	//活动状态
	const STATUS_PREPARE	=0;//待上线
	const STATUS_ONLINE		=1;//线上
	const STATUS_FINISH		=2;//已结束



	//积分抽奖
	public function turnLotteryList(){

		$page		= I('get.p',0,'intval');
		$pageSize 	= I('get.limit',10,'int');	//每页显示条数
		$beginDate 	= I('get.beginDate');	//开始日期
		$endDate 	= I('get.endDate');		//结束日期
		$title 		= I('get.title');		//活动标题


		$where = ' 1  ';
		if ($beginDate){
			$startTimestamp=strtotime($beginDate);
			$where .=" and  addTime >=".$startTimestamp;
		}
		if ($endDate){
			$endTimestamp=strtotime($endDate);
			$where .=" and  addTime <".($endTimestamp+UtilsModel::ONE_DAY);
		}
		if ($title){
			$where .= " and  title like '%{$title}%'";
		}

		$count = TurnModel::getSetInstance()->where($where)->count();
		$this->smarty->assign('totalDataCount',$count);

		$limit = I('get.limit',10,'int');	//每页显示条数
		$Page = new Page($count,$limit);
		fetchPage($this->smarty, $Page);

		$list = TurnModel::getSetInstance()->where($where)->order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();

		$this->smarty->assign('list',$list);

		$turnCountKv=TurnModel::getMappingInstance()->group('turn')->getField('turn,count(1)');


		$this->smarty->assign('turnCountKv',$turnCountKv);

		$this->smarty->assign('page',$page);
		$this->smarty->assign('limit',$pageSize);
		$this->smarty->assign('beginDate',$beginDate);
		$this->smarty->assign('endDate',$endDate);
		$this->smarty->assign('title',$title);

		$this->smarty->display("TurnLottery/dialLottery.html");
	}

	public function turnEdit(){
		$id=I('get.id',0,'intval');


		$type = C('ELEMENT_TYPE');
		$type[0]='谢谢参与';

		$this->smarty->assign('type',$type);
		$cardM = M("card_base_info",null,DB_MAIN_CFG);
		$cardInfo = $cardM->where("stock > 0")->field('id,title')->select();
		$cardID = array();
		$cardTitle = array();
		foreach($cardInfo as $val){
			$cardID[] = $val['id'];
			$cardTitle[] = $val['title'];
		}
		$this->smarty->assign('cardID',$cardID);
		$this->smarty->assign('cardTitle',$cardTitle);

		$data = TurnModel::getSetInstance()->where('id='.$id)->find();
		$item = TurnModel::getItemInstance()->where('setId='.$id)->select();



		$this->smarty->assign('obj',$data);
		$this->smarty->assign('item',$item);

		$this->smarty->assign('num',8);//配置中奖项数量
		$this->smarty->display("TurnLottery/dialLottery_edit.html");
	}

	//保存大转盘配置
	public function saveLuckyInfo(){

		$setId	= I('get.setId',0,'intval');
		$title	= I('get.title');
		$desc	= I('get.desc');

		$prizeId = I('get.prizeId');
		$prizeRank = I('get.prizeRank');
		$prizeName = I('get.prizeName');
		$hitRate = I('get.hitRate');
		$dayLimitTimes = I('get.dayLimit');
		$allLimitTimes = I('get.allLimit');
		$prizeNum = I('get.prizeNum');
		$prizePic = I('get.prizePic');
		$prizeType = I('get.prizeType');
		$extra = I('get.prizeSet');

		//检查奖品名称是否填写完整
		foreach ($prizeName as $key => $val){
			if(!$val){
				$this->ajaxReturn(array('status' => 1, 'msg' => "请填写奖品名称", 'id' => $key));
			}
		}

		//判断中奖率是否为1
		$totalRate=round(array_sum($hitRate)*100000);
		if($totalRate != 100000){
			$this->ajaxReturn(array('status' => 2, 'msg' => "中奖率总和为不等于1，请重新配置"));
		}

		//检查奖品图片是否填写完整
		foreach ($prizePic as $key=>$val){
			if(!$val){
				//$this->ajaxReturn(array('status' => 5,'msg' => "请选择奖品图片",'id' => $key));
			}
		}


        //核实库存是否足够
		if(!$setId){//新增
			//卡券数量核实
			$cardNum=array();
			foreach($prizeType as $k => $v) {
				if ($v == ELEMENT_TYPE_CARD) {
					if (!$extra[$k] || $extra[$k] <= 0) {
						$this->ajaxReturn(array('status' => 6, 'msg' => "请选择奖品卡券", 'id' => $k));
					} elseif ($prizeNum[$k] > 0) {
						//可用数量
						$cardId=$extra[$k];
						if (!array_key_exists($cardId,$cardNum)){
							$cardNum[$cardId] = CouponModel::getAvailableCardNum($cardId);
						}
						if($cardNum[$cardId] < $prizeNum[$k]) {
							$this->ajaxReturn(array('status' => 6, 'msg' => "指定的卡券库存不够分配", 'id' => $k));
						}
						$cardNum[$cardId] -= $prizeNum[$k];
					}
				}elseif($v == ELEMENT_TYPE_POINT){
					if($extra[$k]<=0 || !$extra[$k]){
						$this->ajaxReturn(array('status' => 3, 'msg' => "请正确输入中奖积分" ,'id' => $k));
					}
				} elseif ($v == ELEMENT_TYPE_ECOUPONS){
					if($extra[$k] <=0 || !$extra[$k]){
						$this->ajaxReturn(array('status' => 7, 'msg' => "请正确选择异业券" ,'id' => $k));
					}
				}
			}
		}
		else{//修改
			//卡券数量核实
			$cardNum=array();
			foreach($prizeType as $k => $v){
				if($v == ELEMENT_TYPE_CARD){
					if(!$extra[$k] || $extra[$k] <= 0){
						$this->ajaxReturn(array('status' => 6, 'msg' => "请选择奖品卡券" ,'id' => $k));
					} elseif($prizeNum[$k] > 0){
						//可用数量
						$cardId=$extra[$k];
						if (!array_key_exists($cardId,$cardNum)){
							$cardNum[$cardId] = CouponModel::getAvailableCardNum($cardId);
						}

						//已分配数量
						$assignedUsableNum = M('card_code',null,DB_MAIN_CFG)->where("objType=".OBJ_TYPE_LUCKY." and objID={$prizeId[$k]} and cardId={$extra[$k]}")->count();
						//需要再分配的值
						$needNum = $prizeNum[$k] - $assignedUsableNum;
						if($needNum < 0){//少于已分配数量
							$this->ajaxReturn(array('status' => 4, 'msg' => "该奖项已分配该卡券".$assignedUsableNum."张，请输入不小于该数值的值" ,'id' => $k));
						} elseif($needNum > 0){//大于已分配数量

							if($needNum > $cardNum[$cardId]) {//大于库存
								$this->ajaxReturn(array('status' => 6, 'msg' => "指定的卡券库存不够分配", 'id' => $k));
							}
							$cardNum[$cardId] -= $needNum;
						}else{
							//不分配
						}
					} else{
						$this->ajaxReturn(array('status' => 4, 'msg' => "请输入卡券奖品数量" ,'id' => $k));
					}
				} elseif($v == ELEMENT_TYPE_POINT){
					if($extra[$k]<=0 || !$extra[$k]){
						$this->ajaxReturn(array('status' => 3, 'msg' => "请正确输入中奖积分" ,'id' => $k));
					}
				} elseif ($v == ELEMENT_TYPE_ECOUPONS){
					if($extra[$k] <=0 || !$extra[$k]){
						$this->ajaxReturn(array('status' => 7, 'msg' => "请正确选择异业券" ,'id' => $k));
					}
				}
			}
		}



		$data = array();
		foreach($prizeId as $key => $val){
			$data[$key]['prizeRank'] = $prizeRank[$key];
			$data[$key]['prizeName'] = $prizeName[$key];
			$data[$key]['prizeType'] = $prizeType[$key];
			$data[$key]['hitRate'] = $hitRate[$key];
			$data[$key]['dayLimitTimes'] = $dayLimitTimes[$key];
			$data[$key]['allLimitTimes'] = $allLimitTimes[$key];
			$data[$key]['prizeNum'] = $prizeNum[$key];
			$data[$key]['extra'] = $extra[$key];
			$data[$key]['prizePic'] = $prizePic[$key];
		}

		if(!$setId){//新增
			TurnModel::getSetInstance()->startTrans();
			$setId=TurnModel::getSetInstance()->add(array('title'=>$title,'desc'=>$desc,'addTime'=>time()));
			if ($setId===false){
				TurnModel::getSetInstance()->rollback();
				$this->ajaxReturn(array('status' => '1', 'msg' => '添加活动失败'));
			}
			foreach($data as $k=>$v){
				$v['setId']=$setId;
				$result = TurnModel::getItemInstance()->add($v);
				if(false === $result && 0 === $result) {
					TurnModel::getSetInstance()->rollback();
					$this->ajaxReturn(array('status' => '1', 'msg' => '第'.($k+1).'条更改失败'));
				}else{
					if($prizeType[$k] == ELEMENT_TYPE_CARD){
						if($prizeNum[$k] > 0){
							$result=M('card_code',null,DB_MAIN_CFG)
								->where("cardId=$extra[$k] and status=".CouponModel::CODE_STATUS_DEFAULT." and objType=".OBJ_TYPE_ALL)
								->limit($v['prizeNum'])
								->setField(array('objType'=>OBJ_TYPE_LUCKY,'objID'=>$prizeId[$k]));
							if ($result === false){
								TurnModel::getSetInstance()->rollback();
								$this->ajaxReturn(array('status' => '1', 'msg' => '第'.($k+1).'条更改失败'));
							}
						}
					}
				}
			}
			TurnModel::getSetInstance()->commit();
		}
		else{
			TurnModel::getSetInstance()->startTrans();
			TurnModel::getSetInstance()->where('id='.$setId)->save(array('title'=>$title,'desc'=>$desc,'addTime'=>time()));
			foreach($data as $k=>$v){
				$result = TurnModel::getItemInstance()->where('id='.$prizeId[$k])->save($v);
				if(false === $result && 0 === $result) {
					TurnModel::getSetInstance()->rollback();
					$this->ajaxReturn(array('status' => '1', 'msg' => '第'.($k+1).'条更改失败'));
				}else{
					if($prizeType[$k] == ELEMENT_TYPE_CARD){

						//已分配数量
						$assignedUsableNum = M('card_code',null,DB_MAIN_CFG)->where("objType=".OBJ_TYPE_LUCKY." and objID={$prizeId[$k]} and cardId={$extra[$k]}")->count();
						//需要再分配的值
						$needNum = $prizeNum[$k] - $assignedUsableNum;
						if($needNum > 0){
							$result=M('card_code',null,DB_MAIN_CFG)
								->where("cardId=$extra[$k] and status=".CouponModel::CODE_STATUS_DEFAULT." and objType=".OBJ_TYPE_ALL)
								->limit($needNum)
								->setField(array('objType'=>OBJ_TYPE_LUCKY,'objID'=>$prizeId[$k]));
							if ($result === false){
								TurnModel::getSetInstance()->rollback();
								$this->ajaxReturn(array('status' => '1', 'msg' => '第'.($k+1).'条更改失败'));
							}
						}
					}
				}
			}
			TurnModel::getSetInstance()->commit();
		}

		$this->ajaxReturn(array('status' => '0','msg'=>'保存成功'));
	}


	public function delete(){
		$id=I('get.id',0,'intval');
		TurnModel::getItemInstance()->where("setId={$id}")->delete();
		TurnModel::getSetInstance()->where("id={$id}")->delete();
		$this->ajaxReturn(array('status'=>0,'msg'=>'操作成功'));
	}



	public function deleteMapping(){
		$id=I('get.mid',0,'intval');
		TurnModel::getMappingInstance()->where("id={$id}")->delete();
		//TurnModel::getSetInstance()->where("id={$id}")->delete();
		$this->ajaxReturn(array('status'=>0,'msg'=>'操作成功'));
	}

	/**
	 * 活动关联
	 */
	public function connect(){
		if (IS_AJAX){
			$rules=array(
				array('title', 'require', '关联名称必须埴写'),
				array('applyStartTime', 'require', '活动开始时间必须填写'),
				array('applyEndTime', 'require', '活动结束时间必须填写'),
				array('gotWay', 'require', '获取条件必须填写'),
				array('turn','require','关联转盘必须选择'),
				array('active', 'require', '关联活动必须选择'),
				array('limit', 'require', '限领次数必须填写'),
			);
			if ($data = TurnModel::getMappingInstance()->validate($rules)->create()) {
				$data['addTime']=time();
				$data['rule']=htmlspecialchars_decode(I('post.rule'));
				$mid=I('post.mid',0,'intval');
				if (!$mid) {
					$id = TurnModel::getMappingInstance()->add($data);
				}else{
					$id = TurnModel::getMappingInstance()->where("id={$mid}")->save($data);
				}


				if($id===false){
					$this->ajaxReturn(array('status'=>1,'msg'=>'添加失败'));
				}else{
					$this->ajaxReturn(array('status'=>0,'msg'=>'添加成功'));
				}
			}else{
				$msg=TurnModel::getMappingInstance()->getError();
				$this->ajaxReturn(array('status'=>1,'msg'=>$msg));
			}
		}
		else {
			$id = I('get.id', 0, 'intval');
			if($id) {
				$this->smarty->assign('selectedTurn', $id);
			}
			else{
				$mid= I('get.mid', 0, 'intval');
				$mapping=TurnModel::getMappingInstance()->where("id={$mid}")->find();
				$this->smarty->assign('mid', $mid);
				$this->smarty->assign('selectedTurn', $mapping['turn']);
				$this->smarty->assign('selectedActive', $mapping['active']);
				$this->smarty->assign('applyStartTime', $mapping['applyStartTime']);
				$this->smarty->assign('applyEndTime', $mapping['applyEndTime']);
				$this->smarty->assign('selectedWay', $mapping['gotWay']);
				$this->smarty->assign('limit', $mapping['limit']);
				$this->smarty->assign('title', $mapping['title']);
				$this->smarty->assign('pointFee', $mapping['pointFee']);
				$this->smarty->assign('rule', $mapping['rule']);
			}


			$turnKv = TurnModel::getSetInstance()->getField('id,title');
			$eventKv = EventsModel::getEventInstance()->order('id desc')->limit(60)->getField('id,title');

			array_unshift($eventKv,"不关联活动");
			$this->smarty->assign('turnKv', $turnKv);
			$this->smarty->assign('eventKv', $eventKv);
			$this->smarty->assign('gotWayKv', TurnModel::getGotWayKv());


			$this->smarty->display("TurnLottery/connect_edit.html");
		}
	}



	public function connectList(){

		$page		= I('get.p',0,'intval');
		$pageSize 	= I('get.limit',10,'int');	//每页显示条数
		$beginDate 	= I('get.beginDate');	//开始日期
		$endDate 	= I('get.endDate');		//结束日期
		$turn 		= I('get.turn');		//转盘
		$active 	= I('get.active');		//活动
		$gotWay 	= I('get.gotWay',null);	//条件

		$where = ' 1 ';
		if ($beginDate){
			$where .=" and applyStartTime >='{$beginDate}'";
		}

		if ($endDate){
			$where .=" and applyStartTime <='{$endDate} 59:59:59'";
		}

		if ($turn>0){
			$where .= ' and turn = '.$turn;
		}

		if ($active>0){
			$where .= ' and active = '.$active;
		}

		if ($gotWay){
			$where .= ' and gotWay = '.$gotWay;
		}

		$count = TurnModel::getMappingInstance()->where($where)->count();
		$this->smarty->assign('totalDataCount',$count);

		$limit = I('get.limit',10,'int');	//每页显示条数
		$Page = new Page($count,$limit);
		fetchPage($this->smarty, $Page);

		$list = TurnModel::getMappingInstance()->where($where)->order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();

		$this->smarty->assign('data',$list);


		$turn='0';
		$active='0';
		foreach($list as $one){
			if($one['turn']>0){
				$turn .=','.$one['turn'];
			}
			if($one['active']>0){
				$active .=','.$one['active'];
			}
		}
		if(strcasecmp($turn,'0') != 0){
			$turnKv=TurnModel::getSetInstance()->where("id in ({$turn})")->getField('id,title');
			$this->smarty->assign('turnKv',$turnKv);
		}

		if(strcasecmp($active,'0')!= 0){
			$activeKv=EventsModel::getEventInstance()->where("id in ({$active})")->getField('id,title');
			$this->smarty->assign('activeKv',$activeKv);
		}



		$this->smarty->assign('page',$page);
		$this->smarty->assign('limit',$pageSize);
		$this->smarty->assign('beginDate',$beginDate);
		$this->smarty->assign('endDate',$endDate);
		$this->smarty->assign('turn',$turn);


		$this->smarty->assign('domain',UtilsModel::getFullDomain());


		$this->smarty->display("TurnLottery/turnMapping.html");
		

	}


	/**
	 * 增加名单
	 */
	public function chance(){
		if (IS_AJAX){
			$mid=I('post.mid',0,'intval');
			$list=I('post.list');
			$uids=preg_split("/[，,]+/",$list);
			$data=array();
			$now=time();
			foreach($uids as $uid){
				if ($uid>0){
					$data[]=array('mid'=>$mid,'uid'=>$uid,'addTime'=>$now,'used'=>0);
				}
			}
			if (count($data)>0){
				TurnModel::getChanceInstance()->where("mid={$mid} and used=0")->delete();
				TurnModel::getChanceInstance()->addAll($data);
				$this->ajaxReturn(array('status'=>0,'msg'=>'添加成功'));
			}
			$this->ajaxReturn(array('status'=>1,'msg'=>'数据不合法'));
		}else{
			$id=I('get.mid',0,'intval');
			$mapping=TurnModel::getMappingInstance()->where("id={$id}")->find();
			if (!$mapping){
				die('参数错误');
			}

			if ($mapping['gotWay']!=TurnModel::GOTWAY_APPLY){
				die('本模式下不可添加名单');
			}
			$uids=TurnModel::getChanceInstance()->where("mid={$id} and used=0")->getField('uid',true);
			if (count($uids)>0){
				$this->smarty->assign('list',implode(',',$uids));
			}

			$this->smarty->assign('mid',$id);
			$this->smarty->display("TurnLottery/chance_edit.html");
		}




	}



	//大转盘抽奖中奖记录
	public function prizeLog(){

		$phone 		= I('get.phone',null);
		$keyword 	= I('get.keyword',null);
		$beginDate 	= I('get.beginDate');
		$endDate 	= I('get.endDate');
		$mapping 	= I('get.mapping');
		$prize 	= I('get.prize');

		$export	=I('get.export',0,'int');

		$mappingKv=TurnModel::getMappingInstance()->getField('id,title');

		$where = "1 ";
		if($phone ){
				$where .= " and turn_join.bindPhone like '%{$phone}%' ";
		}
		if($keyword){
				$where .= " and turn_join.realName like '%{$keyword}%' ";
		}


		if ($beginDate){
			$startTimestamp=strtotime($beginDate);
			$where .=" and  turn_join.addTime >=".$startTimestamp;
		}
		if ($endDate){
			$endTimestamp=strtotime($endDate);
			$where .=" and  turn_join.addTime <".($endTimestamp+UtilsModel::ONE_DAY);
		}
		if ($mapping){
			$where .=" and  turn_join.mid ={$mapping}";
		}

		if ($prize){
			$where .=" and  turn_join.prizeNote like '%{$prize}%'";
		}




		$luckyM =  TurnModel::getJoinInstance();
		$rankOption = SignLuckyModel::getLuckyPrizeStatus();
		unset($rankOption[0]);
		$status = SignLuckyModel::getPrizeAcceptStatus();
		if($export){
			ini_set('memory_limit', '512M');
			$list = $luckyM
				->join('left join u_user_base ON turn_join.uid = u_user_base.uid')
				->field('turn_join.*,u_user_base.province,u_user_base.city,u_user_base.district,u_user_base.street,u_user_base.address,u_user_base.nickname')
				->order('id DESC')
				->where($where)
				->select();
			$uid = array();
			foreach ($list as $v){
				$uid[] = $v['uid'];
			}
			$uid = array_unique($uid);
			$info = array();
			foreach ($uid as $key=>$val){
				foreach ($list as $v){
					if($val == $v['uid']){
						$info[$key]['uid'] = $val;
						$regionKv = include_once(WEB_ROOT.'/data/area_info/'.$v['province'].'.php');
						$info[$key]['address'] = $regionKv[$v['province']]['name']
							.'.'.$regionKv[$v['city']]['name']
							.'.'.$regionKv[$v['district']]['name']
							.'.'.$regionKv[$v['street']]['name']
							.'.'.$v['address'];
						break;
					}
				}
			}

			$data = array();
			foreach ($list as $key => $val){
				$data[$key]['addTime'] = date('Y-m-d H:i:s',$val['addTime']);
				$data[$key]['nickname'] = $val['nickname'];
				$data[$key]['realName'] = $val['realName'];
				$data[$key]['bindPhone'] = $val['bindPhone'];

				$data[$key]['prizeName'] = str_replace('<br/>',',',$val['prizeNote']);
				foreach ($info as $v){
					if($val['uid'] == $v['uid']){
						$data[$key]['address'] = $v['address'];
						break;
					}
				}
				$data[$key]['status'] = $status[$val['status']];

			}
			exportExcel($data, array('中奖时间','用户昵称','用户名称','手机号码','奖品说明','收货地址','发货状态'),'中奖名单_'.date('Ymd',time()));
			exit;
		}
		else{
			$count = $luckyM->where($where)->count();
			$limit = I('get.limit',10,'int');	//每页显示条数
			$Page = new Page($count,$limit);
			fetchPage($this->smarty,$Page);
			$this->smarty->assign('totalDataCount',$count);
			$list = $luckyM
				->join('left join u_user_base ON turn_join.uid = u_user_base.uid')
				->field('turn_join.*,u_user_base.province,u_user_base.city,u_user_base.district,u_user_base.street,u_user_base.address,u_user_base.nickname')
				->where($where)
				->order('id DESC')
				->limit($Page->firstRow . ',' . $Page->listRows)
				->select();

			$uid = array();
			foreach ($list as $v){
				$uid[] = $v['uid'];
			}
			$uid = array_unique($uid);
			$info = array();
			foreach ($uid as $key=>$val){
				foreach ($list as $v){
					if($val == $v['uid']){
						$info[$key]['uid'] = $val;
						$regionKv = include_once(WEB_ROOT.'/data/area_info/'.$v['province'].'.php');
						$info[$key]['address'] = $regionKv[$v['province']]['name']
							.'.'.$regionKv[$v['city']]['name']
							.'.'.$regionKv[$v['district']]['name']
							.'.'.$regionKv[$v['street']]['name']
							.'.'.$v['address'];
						break;
					}
				}
			}

			foreach ($list as $key => $val){
				foreach ($info as $v){
					if($val['uid'] == $v['uid']){
						$list[$key]['address'] = $v['address'];
						break;
					}
				}
				$list[$key]['prizeRank'] = $rankOption[$val['prizeRank']];
				$list[$key]['prizeName'] = $val['prizeNote'];
				$list[$key]['statusText'] = $status[$val['status']];
			}

			$this->smarty->assign('data',$list);
			$this->smarty->assign('limit',$limit);
			$this->smarty->assign('keyword',$keyword);
			$this->smarty->assign('beginDate',$beginDate);
			$this->smarty->assign('endDate',$endDate);
			$this->smarty->assign('phone',$phone);
			$this->smarty->assign('mapping',$mapping);
			$this->smarty->assign('mappingKv',$mappingKv);
			$this->smarty->assign('prize',$prize);
			$this->smarty->display('TurnLottery/prizeLog.html');


		}

	}
}
